package cuiyt.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cyt
 * @create 2020-05-03 23:03
 */
public class demo02 {

    public static void main(String[] args) {
        people2 people = new people2();

        // 开启线程
        new Thread(() -> {
            people.say();
        }, "A").start();

        // 开启线程
        new Thread(() -> {
            people.say();
        }, "B").start();
    }
}

class people2 {

    Lock lock = new ReentrantLock();

    public void say() {
        lock.lock();
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "say");
            walk(); // 在拿到 say 调用者锁后， 又重新获得了一次walk调用者的锁
            // 可以多次获得一把锁， 而不会出现死锁的问题
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            lock.unlock();
        }
    }

    public void walk() {

        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "walk");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
